<?php

namespace App\Models;

use Illuminate\Support\Facades\Cache;

class Region extends Base
{
    protected $table = 'regions';

    protected $guarded = [];


    /**
     * 获取树状结构
     *
     * @param bool $isUpdate 是否更新
     */
    public static function getTreeDatas($isUpdate = false)
    {
        $cacheKey = 'cache-tree_region';
        if ($isUpdate) {
            Cache::forget($cacheKey);
        }
        $list = Cache::get($cacheKey);
        if (!$list) {
            $where = [
                ['level', '<', 3]
            ];
            $list = self::where($where)->get()->toArray();
            if ($list) {
                // 处理列表数据
                $list = list_to_tree($list, 'area_code', 'parent_code', 'children', 0);
            }
            Cache::forever($cacheKey, $list); // 永久存储
        }

        return $list;
    }
}
